package com.ishare.admin.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ishare.admin.mapper.SysUserTokenMapper;
import com.ishare.admin.oauth2.TokenGenerator;
import com.ishare.admin.service.SysUserTokenService;
import com.ishare.common.entity.po.SysUser;
import com.ishare.common.entity.po.SysUserToken;
import com.ishare.common.wrapper.Wrapper;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;


@Service("sysUserTokenService")
public class SysUserTokenServiceImpl extends ServiceImpl<SysUserTokenMapper, SysUserToken> implements SysUserTokenService {
    //24小时后过期
    private final static int EXPIRE = 3600 * 24;


    @Override
    public Wrapper createToken(SysUser user) {
        //生成一个token
        String token = TokenGenerator.generateValue();

        //当前时间
        Date now = new Date();
        //过期时间
        Date expireTime = new Date(now.getTime() + EXPIRE * 1000);

        //判断是否生成过token
        SysUserToken tokenEntity = this.getById(user.getId());
        if (tokenEntity == null) {
            tokenEntity = new SysUserToken();
            tokenEntity.setUserId(user.getId());
            tokenEntity.setToken(token);
            tokenEntity.setUpdateTime(now);
            tokenEntity.setExpireTime(expireTime);

            //保存token
            this.save(tokenEntity);
        } else {
            tokenEntity.setToken(token);
            tokenEntity.setUpdateTime(now);
            tokenEntity.setExpireTime(expireTime);

            //更新token
            this.updateById(tokenEntity);
        }
        Map<String,Object> map = new HashMap<>();
        user.setPwd(null);
        user.setSalt(null);
        user.setPhone(null);
        map.put("token", token);
        map.put("user", user);
        map.put("expire", EXPIRE);
        return Objects.requireNonNull(Wrapper.ok(map));
    }

    @Override
    public void logout(long userId) {
        //生成一个token
        String token = TokenGenerator.generateValue();

        //修改token
        SysUserToken tokenEntity = new SysUserToken();
        tokenEntity.setUserId(userId);
        tokenEntity.setToken(token);
        this.updateById(tokenEntity);
    }

    @Override
    public SysUserToken queryByToken(String token) {
        return baseMapper.queryByToken(token);
    }
}
